package com.gao.security.autoconfig.bb;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gao.security.verificationcode.code.VerificationCodeGenerationStrategy;
import com.gao.security.verificationcode.common.RequestPathType;
import com.gao.security.verificationcode.common.VerificationCodeConstants;
import com.gao.security.verificationcode.entity.VerificationCode;
import com.gao.security.verificationcode.exception.ValidateCodeIncorrectException;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.security.util.SecurityConstants;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2019-08-01 10:55
 */
@Component
public class ImgVerificationCodeGenerationStrategy implements VerificationCodeGenerationStrategy {

    @Autowired
    private  DefaultKaptcha kaptcha;

    @Override
    public String createCode() {
        return kaptcha.createText();
    }

    @Override
    public void sendCode(HttpServletRequest request, HttpServletResponse response, VerificationCode code) throws IOException {
        response.setContentType("image/jpeg");
        //禁止图像缓存
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control", "no-cache");
        //在代理服务器端防止缓冲
        response.setDateHeader("Expires", 0);
        response.setHeader(VerificationCodeConstants.VALIDATE_CODE_KEY,code.getCodeToken());
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(kaptcha.createImage(code.getCode()), "jpg", response.getOutputStream());
        // 关闭流
        outputStream.close();
    }

    @Override
    public VerificationCode check(HttpServletRequest request) {
        String code = request.getParameter(VerificationCodeConstants.VALIDATE_CODE);
        String codeToken = request.getHeader(VerificationCodeConstants.VALIDATE_CODE_KEY);
        if(code==null&&codeToken==null){
            throw new ValidateCodeIncorrectException("错误的参数请求头");
        }
        return new VerificationCode(code,codeToken);
    }



    @Override
    public RequestPathType requestPathType() {
        return RequestPathType.IMG;
    }


}
